<template>
	<view class="category">
		<view class="row add" @click="clickAdd">
			<view class="left">
				<u-icon name="plus"  size="20" color="#31b7ff"></u-icon>
				<text>新增分类</text>
			</view>
			
		</view>
		<view class="row" v-for="(item,index) in catrgoryList" :key="item._id">
			<view class="left">
				<view class="name">{{item.name}}</view>
			</view>
			<view class="right">
				<u-icon name="edit-pen"  size="26" color="#31b7ff" @click="updateData(item._id,item.name)"></u-icon>
				<u-icon name="trash"  size="26" color="#ee4f52" @click="deleteData(item._id)"></u-icon>		
			</view>
		</view>
		<view>
			<!-- 输入框示例 -->
			<uni-popup ref="inputDialog">
				<uni-popup-dialog 
					mode="input"
					title="请输入分类名称" 
					:value="iptValue"
					placeholder="请输入分类名称" 
					@confirm="dialogInputConfirm">
				</uni-popup-dialog>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	const db = uniCloud.database();
	export default {
		data() {
			return {
				catrgoryList:[],
				iptValue:"",
				updataId:null
				
			};
		},
		onLoad() {
			this.isManage()
			this.getCateGory()
		},
		methods:{
			getCateGory(){
				db.collection("wanshop-mall-categories").get().then(res =>{
					this.catrgoryList = res.result.data
					console.log(res);
				})
			},
			clickAdd(){
				this.iptValue = ""
				this.updataId = null
				this.$refs.inputDialog.open()
			},
			dialogInputConfirm(e){
				this.iptValue = e;
				
				if(this.updataId){
					db.collection("wanshop-mall-categories").doc(this.updataId).update({
							name:this.iptValue,
				}).then(()=>{
					uni.showToast({
						title:"修改成功"
					});
					this.getCateGory();
				})
					
				}else{
					db.collection("wanshop-mall-categories").add({name:this.iptValue}).then(res =>{
					console.log(res);
					uni.showToast({
						title:"新增分类成功"
					})
					this.getCateGory(); 
				})
				}
				
				
				
				
				// this.catrgoryList.push({
				// 	name:this.iptValue,
				// 	_id:Date.now()
				// }),
				
			},
			// 删除分类
			deleteData(id){
				uni.showModal({
					content:"是否删除该分类？",
					success:res=>{
						if(res.confirm){
							db.collection("wanshop-mall-categories").doc(id).remove().then(()=>{
								uni.showToast({
									title:"分类删除成功",
								});
								this.getCateGory();
							})
						}
					},
					fail: err => {
						console.log("删除"+id);
					}
					
				})
			},
			// 更新分类
			updateData(id,name){
				this.iptValue = name;
				this.updataId = id;
				this.$refs.inputDialog.open()
			}
		}
	}
</script>

<style lang="scss">
	.category{
		padding: 30rpx;
		.row{
			@include flex-box();
			border-bottom:1px solid $border-color-light ;
			padding: 26rpx 0;
			.left{
				font-size: 34rpx;
			}
			.right{
				@include flex-box();
				.u-icon{
					margin-left: 30rpx;
				}
			}
		}
		.row.add{
			.left{
				color:#31b7ff;
				@include flex-box();
				text{
					font-size: 30rpx;
					margin-left: 10rpx;
				}
			}
		}
	}
</style>
